<template>
  <div class="papers-list">
    <div class="page-header">
      <h2>学术论文管理</h2>
      <el-button
        v-if="isStudent"
        type="primary"
        @click="$router.push('/papers/create')"
      >
        <el-icon><Plus /></el-icon>
        添加论文
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="论文名称">
          <el-input
            v-model="searchForm.paperTitle"
            placeholder="请输入论文名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="期刊名称">
          <el-input
            v-model="searchForm.journal"
            placeholder="请输入期刊名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="检索级别">
          <el-select
            v-model="searchForm.indexLevel"
            placeholder="请选择检索级别"
            clearable
          >
            <el-option label="SCI" value="SCI" />
            <el-option label="EI" value="EI" />
            <el-option label="CSSCI" value="CSSCI" />
            <el-option label="CSCD" value="CSCD" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.auditStatus"
            placeholder="请选择审核状态"
            clearable
          >
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <template #empty>
          <EmptyState
            title="暂无论文数据"
            description="还没有添加任何学术论文，点击下方按钮开始添加"
          >
            <template #action>
              <el-button
                v-if="isStudent"
                type="primary"
                @click="$router.push('/papers/create')"
              >
                <el-icon><Plus /></el-icon>
                添加论文
              </el-button>
            </template>
          </EmptyState>
        </template>
        <el-table-column prop="paperTitle" label="论文名称" min-width="200" />
        <el-table-column prop="journal" label="期刊" width="150" />
        <el-table-column prop="indexLevel" label="检索级别" width="100" />
        <el-table-column prop="firstAuthor" label="第一作者" width="120" />
        <el-table-column prop="correspondingAuthor" label="通讯作者" width="120" />
        <el-table-column prop="impactFactor" label="影响因子" width="100" />
        <el-table-column prop="publishDate" label="发表日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.publishDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">
              查看
            </el-button>
            <el-button
              v-if="canEdit(row)"
              type="text"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="canDelete(row)"
              type="text"
              @click="handleDelete(row)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
            <el-button
              v-if="canAudit(row)"
              type="text"
              @click="handleAudit(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="论文详情"
      width="800px"
    >
      <div v-if="currentPaper" class="paper-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="论文名称" :span="2">
            {{ currentPaper.paperTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="期刊">
            {{ currentPaper.journal }}
          </el-descriptions-item>
          <el-descriptions-item label="期号">
            {{ currentPaper.issueNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="卷号">
            {{ currentPaper.volumeNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="页码">
            {{ currentPaper.pageNumbers }}
          </el-descriptions-item>
          <el-descriptions-item label="检索级别">
            {{ currentPaper.indexLevel }}
          </el-descriptions-item>
          <el-descriptions-item label="影响因子">
            {{ currentPaper.impactFactor }}
          </el-descriptions-item>
          <el-descriptions-item label="第一作者">
            {{ currentPaper.firstAuthor }}
          </el-descriptions-item>
          <el-descriptions-item label="通讯作者">
            {{ currentPaper.correspondingAuthor }}
          </el-descriptions-item>
          <el-descriptions-item label="发表日期">
            {{ formatDate(currentPaper.publishDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="论文链接" :span="2">
            <el-link
              v-if="currentPaper.paperLink"
              :href="currentPaper.paperLink"
              target="_blank"
              type="primary"
            >
              {{ currentPaper.paperLink }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="作者名单" :span="2">
            {{ currentPaper.authorList }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentPaper.auditStatus)">
              {{ getStatusText(currentPaper.auditStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentPaper.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { paperAPI } from '@/api/paper'
import EmptyState from '@/components/EmptyState.vue'

export default {
  name: 'PapersList',
  components: {
    Plus,
    Search,
    Refresh,
    EmptyState
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(false)
    const tableData = ref([])
    const detailDialogVisible = ref(false)
    const currentPaper = ref(null)

    const searchForm = reactive({
      paperTitle: '',
      journal: '',
      indexLevel: '',
      auditStatus: ''
    })

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const isStudent = computed(() => store.getters.isStudent)
    const isTeacher = computed(() => store.getters.isTeacher)
    const userInfo = computed(() => store.getters.userInfo)

    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage - 1,
          size: pagination.pageSize,
          ...searchForm
        }

        const response = await paperAPI.getPapers(params)
        // 后端返回的是简单数组，不是分页对象
        tableData.value = response.data || []
        pagination.total = response.data ? response.data.length : 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadData()
    }

    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      loadData()
    }

    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadData()
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadData()
    }

    const handleView = (row) => {
      currentPaper.value = row
      detailDialogVisible.value = true
    }

    const handleEdit = (row) => {
      router.push(`/papers/edit/${row.id}`)
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这篇论文吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await paperAPI.deletePaper(row.id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const handleAudit = (row) => {
      ElMessage.info('审核功能开发中')
    }

    const canEdit = (row) => {
      return isStudent.value &&
             row.userId === userInfo.value.id &&
             row.auditStatus !== 'APPROVED'
    }

    const canDelete = (row) => {
      return isStudent.value &&
             row.userId === userInfo.value.id &&
             row.auditStatus !== 'APPROVED'
    }

    const canAudit = (row) => {
      return isTeacher.value && row.auditStatus === 'PENDING'
    }

    const getStatusText = (status) => {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝',
        4: '待审核',  // 兼容后端数据
        5: '待审核'   // 兼容后端数据
      }
      return statusMap[status] || '未知状态'
    }

    const getStatusType = (status) => {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
        4: 'warning',  // 兼容后端数据
        5: 'warning'   // 兼容后端数据
      }
      return typeMap[status] || 'info'
    }

    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleDateString('zh-CN')
    }

    onMounted(() => {
      loadData()
    })

    return {
      loading,
      tableData,
      searchForm,
      pagination,
      detailDialogVisible,
      currentPaper,
      isStudent,
      isTeacher,
      loadData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleEdit,
      handleDelete,
      handleAudit,
      canEdit,
      canDelete,
      canAudit,
      getStatusText,
      getStatusType,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.papers-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .search-card {
    margin-bottom: 20px;

    // 响应式搜索表单
    :deep(.el-form--inline) {
      .el-form-item {
        margin-right: 16px;
        margin-bottom: 16px;
      }
    }
  }

  .table-card {
    // 表格响应式容器
    :deep(.el-table) {
      .el-table__body-wrapper {
        overflow-x: auto;
      }
    }

    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }

  .paper-detail {
    .el-descriptions {
      margin-top: 20px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .papers-list {
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          width: calc(50% - 8px);
          margin-right: 8px;

          .el-input,
          .el-select {
            width: 100%;
          }
        }

        .el-form-item:nth-child(odd) {
          margin-right: 16px;
        }

        .el-form-item:nth-child(even) {
          margin-right: 0;
        }

        // 按钮组单独一行
        .el-form-item:last-child {
          width: 100%;
          margin-right: 0;
          text-align: center;

          .el-button {
            margin: 0 8px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .papers-list {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      h2 {
        font-size: 20px;
      }

      .el-button {
        width: 100%;
      }
    }

    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          width: 100%;
          margin-right: 0;

          .el-input,
          .el-select {
            width: 100%;
          }
        }

        // 按钮组
        .el-form-item:last-child {
          .el-button {
            width: calc(50% - 8px);
            margin: 0 4px;
          }
        }
      }
    }

    .table-card {
      // 移动端表格优化
      :deep(.el-table) {
        font-size: 12px;

        .el-table__header th {
          padding: 8px 4px;
          font-size: 12px;
        }

        .el-table__body td {
          padding: 8px 4px;
          font-size: 12px;
        }

        // 隐藏部分列在移动端
        .el-table-column--selection,
        .el-table__column:nth-child(6), // 影响因子
        .el-table__column:nth-child(7)  // 发表日期
        {
          display: none;
        }
      }

      .pagination-container {
        text-align: center;

        :deep(.el-pagination) {
          .el-pagination__sizes,
          .el-pagination__jump {
            display: none;
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .papers-list {
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item:last-child {
          .el-button {
            width: 100%;
            margin: 4px 0;
          }
        }
      }
    }

    .table-card {
      :deep(.el-table) {
        // 进一步隐藏列
        .el-table__column:nth-child(3), // 检索级别
        .el-table__column:nth-child(5)  // 通讯作者
        {
          display: none;
        }
      }
    }
  }
}
</style>
